package com.cryptoneedle.center.doris.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.cryptoneedle.center.doris.service.doris.*;
import com.cryptoneedle.center.doris.service.dwd.DwdSyncService;
import com.cryptoneedle.center.doris.service.ods.OdsSyncService;
import com.cryptoneedle.center.doris.service.standard.StandardSyncService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>description: Doris 服务 </p>
 *
 * @author CryptoNeedle
 * @date 2025-09-25
 */
@Service
@DS("pg")
@Slf4j
public class DorisService {

    @Resource
    private DorisSyncService dorisSyncService;

    @Resource
    private DorisCatalogService dorisCatalogService;

    @Resource
    private DorisDatabaseService dorisDatabaseService;

    @Resource
    private DorisTableService dorisTableService;

    @Resource
    private OdsSyncService odsSyncService;

    @Resource
    private DwdSyncService dwdSyncService;

    @Resource
    private StandardSyncService standardSyncService;

    @Resource
    private DorisColumnService dorisColumnService;

    private final ReentrantLock syncLock = new ReentrantLock();

    // todo 通用化
    public boolean trySync() {
        if (!syncLock.tryLock()) {
            return false;
        }

        try {
            // 执行你的同步逻辑
            sync();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            syncLock.unlock();
        }
    }

    private void sync() {
        // 同步 Doris Table
        dorisSyncService.syncDoris();
        // 同步 ODS Table
        odsSyncService.syncOds();
        // 同步 DWD Table
        dwdSyncService.syncDwd();
        // 同步 Standard Table
        standardSyncService.syncStandard();
    }

    public void syncColumn(String catalogName, String databaseName, String tableName) {
        // 同步 Doris Column
        dorisSyncService.syncDorisColumn(catalogName, databaseName, tableName);
        // 同步 ODS Column
        odsSyncService.syncOdsColumn(catalogName, databaseName, tableName);
        // 同步 DWD Column
        dwdSyncService.syncOdsColumn(catalogName, databaseName, tableName);
        // 同步 Standard Table
        standardSyncService.syncStandardColumn(catalogName, databaseName, tableName);
    }
}